package com.yiwei.jmx;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yiwei.jmx.activity.BankBindActivity;
import com.yiwei.jmx.activity.CarIdentityActivity;
import com.yiwei.jmx.activity.FaceIdentityActivity;
import com.yiwei.jmx.activity.FaceIdentityZhiMaActivity;
import com.yiwei.jmx.activity.HouseIdentityActivity;
import com.yiwei.jmx.activity.IdcardIdentityActivity;
import com.yiwei.jmx.activity.IdentityContactActivity;
import com.yiwei.jmx.activity.IncomeIdentityActivity;
import com.yiwei.jmx.activity.V3XueXinIdentityActivity;
import com.yiwei.jmx.activity.WorkIdentityActivity;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.LiMuKeyBean;
import com.yiwei.jmx.api.bean.LiMuSignBean;
import com.yiwei.jmx.api.bean.LiMuTokenBean;
import com.yiwei.jmx.api.model.UserModel;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.event.ChangeHomePageEvent;
import com.yiwei.jmx.event.LoginSuccessEvent;
import com.yiwei.jmx.event.UserEvent;
import com.yiwei.jmx.event.UserUnLoginEvent;
import com.yiwei.jmx.fragment.MainDiscoverFragment;
import com.yiwei.jmx.fragment.MainHomeFragment;
import com.yiwei.jmx.fragment.MainMyFragment;
import com.yiwei.jmx.fragment.MainPrizeFragment;
import com.yiwei.jmx.fragment.MainRiskFragment;
import com.yiwei.jmx.util.AppDownloadManager;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.DownloadUtil;
import com.yiwei.jmx.util.FileUtils;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.PreferenceUtils;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.BussinessBottomLayout;
import com.yiwei.jmx.view.SuperViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import kangcheng.com.lmzx_android_sdk_v10.bean.Fuction;
import kangcheng.com.lmzx_android_sdk_v10.bean.MessageEvent;
import kangcheng.com.lmzx_android_sdk_v10.bean.SignEvent;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSDK;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSdkImpl;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.DataCallBack;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.ObservableManager;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class MainActivity extends BaseActivity implements BussinessBottomLayout.OnChooseListener, DataCallBack {


    @BindView(R.id.pager)
    SuperViewPager pager;
    @BindView(R.id.bottom_menu)
    BussinessBottomLayout bottomMenu;
    //    @BindView(R.id.container)
//    FrameLayout container;
    private Fragment[] mFragments = new Fragment[4];
    private Unbinder unbiner;

    private int curIndex;
    private AppDownloadManager appDownloadManager;
    public boolean initSuccess = false;
    public String bizType;
    public boolean isFail = false;
    public final static String SUCCESS = "0";
    public final static String LOGING_SUCCESS = "2";

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putInt("curIndex", curIndex);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bussiness_main);
        initBarTouming();
        unbiner = ButterKnife.bind(this);
        if (savedInstanceState != null) {
            curIndex = savedInstanceState.getInt("curIndex");
        }
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        mFragments[0] = new MainHomeFragment();
        mFragments[1] = new MainPrizeFragment();
        mFragments[2] = new MainRiskFragment();
//        mFragments[3] = new MainDiscoverFragment();
        mFragments[3] = new MainMyFragment();

        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {

                return mFragments[position];
            }

            @Override
            public int getCount() {
                return mFragments.length;
            }

        });
        pager.setOffscreenPageLimit(3);
        bottomMenu.setOnChooseListener(this);
    }

    @Override
    public void onClick(int poi) {
        pager.setCurrentItem(poi);
    }


    private static long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(this,
                        "再按一次退出",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                this.finish();
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LmzxSdkImpl.getInstance().unRegistEvet();
        unbiner.unbind();
        unbiner = null;
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginSuccessEvent msg) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ChangeHomePageEvent msg) {
        bottomMenu.setSelectPage(msg.page);
    }

    /**
     * 检查版本
     */
    public void checkUpdate() {
        FileUtils.delFile(Const.APP_NAME); //删除安装包

        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        String url = PreferenceUtils.getString(this, "download_url", "");


        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(url))
            return;

        try {
            String versionName = Util.getVersion(this);
            versionName = versionName.replace("", "");

            String versionNew = version.replace("", "");

            if (compareVersion(versionNew, versionName) > 0) {
//                isFirstTips = false;

                appDownloadManager = new AppDownloadManager(this);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    /**
     * 获取权限回调 兼容6.0
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功

                appDownloadManager.initDownloadManager();
            } else {
                // 获取权限失败
                ToastUtil.makeText(this, "获取权限失败~");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUser();
        if (appDownloadManager != null) {
            return;
        }
        checkUpdate();
    }

    public void getUser() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        Api.api_service.getUser().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1) {
                        UserInfoGlobal.saveUserInfo(result);
                        EventBus.getDefault().post(new UserEvent(result));
                    } else {
                        EventBus.getDefault().post(new UserUnLoginEvent());
                        UserInfoGlobal.user_info = null;
                    }

                });
    }

    public void getKey(String deal_id, boolean isOperator) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuKeyBean bean = new LiMuKeyBean();
        bean.deal_id = deal_id;
        Api.api_service.getLiMuKey(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    //    初始化立木
                    if (result.getStatus() == 1) {
                        Application.getInstance().LmsdkInit(result.getData().getKey(), result.getData().getUid());
                        LmzxSDK sdk = LmzxSdkImpl.getInstance();
                        sdk.registEvent(this);
                        sdk.setTextStyle(this, 0xFF4a4a4a);
                        sdk.setButtonStyle(this, 0xFF4C81FF);
                        sdk.setPageBack(this, 0xFFf4f4f4);
                        sdk.setBannerTextColor(this, 0xFFFFFFFF);
                        initSuccess = true;

                        if (!isOperator) {
                            return;
                        }
                        switch (bizType) {
                            case Const.IdentityType.yunyin:

                                if (TextUtils.isEmpty(PreferenceUtils.getString(this, "mobile", "")) || Const.IS_DEBUG) {
                                    LmzxSdkImpl.getInstance().initOperatorPreNo(this, "", true);
                                } else {
                                    LmzxSdkImpl.getInstance().initOperatorPreNo(this, PreferenceUtils.getString(this, "mobile", ""), false);
                                }
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionMobileCarrie, 0 + "", Const.LIMU_CALLBACK);
                                break;
                            case Const.IdentityType.car:
                                Util.startActivity(this, CarIdentityActivity.class);
                                break;

                            case Const.IdentityType.face:
//                                LmzxSdkImpl.getInstance().setHTJCParas(this, "true", "0129", "3", "8", "false", "true");
//                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKHTJC, 0 + "", Const.LIMU_CALLBACK);
                                Util.startActivity(this, FaceIdentityActivity.class);
                                break;
                            case Const.IdentityType.contacts:
                                Util.startActivity(this, IdentityContactActivity.class);
                                break;

                            case Const.IdentityType.email:
//                Util.startActivity(this, V3EmailIdentityActivity.class);
                                break;

                            case Const.IdentityType.face_detect:
                                Util.startActivity(this, FaceIdentityZhiMaActivity.class);
                                break;

                            case Const.IdentityType.house:
                                Util.startActivity(this, HouseIdentityActivity.class);
                                break;

                            case Const.IdentityType.housefund:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionHousingFund, 0 + "", Const.LIMU_CALLBACK);
                                break;

                            case Const.IdentityType.income:
                                Util.startActivity(this, IncomeIdentityActivity.class);
                                break;

                            case Const.IdentityType.jd:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionJD, 0 + "", Const.LIMU_CALLBACK);
                                break;
                            case Const.IdentityType.linkedin:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionLinkedIn, 0 + "", Const.LIMU_CALLBACK);
                                break;

                            case Const.IdentityType.realname:
                                Util.startActivity(this, IdcardIdentityActivity.class);
                                break;

                            case Const.IdentityType.socialsecurity:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionSocialSecurity, 0 + "", Const.LIMU_CALLBACK);
                                break;

                            case Const.IdentityType.taobao:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionTaoBao, 0 + "", Const.LIMU_CALLBACK);
                                break;
                            case Const.IdentityType.work:
                                Util.startActivity(this, WorkIdentityActivity.class);
                                break;
                            case Const.IdentityType.xuexin:
                                Util.startActivity(this, V3XueXinIdentityActivity.class);
                                break;
                            case Const.IdentityType.bankcard:
                                Util.startActivity(this, BankBindActivity.class);
                                break;

                        }
                    }
                });
    }

    public void getSign(String params) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }


        LiMuSignBean bean = new LiMuSignBean();
        bean.params = params;
        Api.api_service.getSign(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("sign", result.getSign());
                    //Log.i("signString", "加签结果" + secondSign);
                    ObservableManager.getInstance().doLogic("sign", hashMap); //加签结果传给sdk。key值必须是"sign"。
                });
    }


    public void uploadToken(String deal_id, String token, String biztype) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuTokenBean bean = new LiMuTokenBean();
        bean.deal_id = deal_id;
        bean.token = token;
        bean.biztype = biztype;
        Api.api_service.uploadToken(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1 && !isFail) {
                        ((MainRiskFragment) mFragments[2]).getAllIdentity();
                        ToastUtil.makeText(this, "认证成功", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void signData(SignEvent signEvent) {
        String sign = signEvent.getSignStr();//r3qUEj6PhkTz8odjHC0OYTXbtlSxqWyQ  //1.收到sdk传来的字符串
        getSign(sign);
    }

    @Override
    public void messageData(MessageEvent event) {
        MessageEvent test = (MessageEvent) event;
//            Log.i("dasdadsadsadsasa", "code" + test.getCode() + ",message" + test.getMessage() + ",token" + test.getToken() + ",function" + test.getFunction() + ",hasmap" + test.getHashMap().toString());

        if (SUCCESS.equals(((MessageEvent) event).getCode())) {
            //具体哪个业务,参看文档的相关业务类型做处理
            int function = ((MessageEvent) event).getFunction();
            //服务密码
            if (function == Fuction.LMZXSDKFunctionMobileCarrie) {
                //...

            }
            //登录成功处理
        } else if (LOGING_SUCCESS.equals(((MessageEvent) event).getCode())) {
            //可以获取token值,记录提交请求,或者忽略掉
            isFail = false;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
            //查询失败
        } else {
            isFail = true;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
            //失败处理,可忽略
//            Log.i("dadasdda", "失败code：" + ((MessageEvent) event).getCode() + "\ntoken=" + ((MessageEvent) event).getToken());
//            Intent intent = new Intent(this, MyIdentityActivity.class);
//            startActivity(intent);
        }
    }
}
